﻿using Gengens.Disk.WebApi.dto.output.file;

namespace Gengens.Disk.WebApi.util
{
    public class FileUtils
    {

        #region 变量

        /// <summary>
        /// 大文件上传，前置缓存
        /// </summary>
        private static List<PreFileInfo> _preFileCache;
        /// <summary>
        /// 大文件上传前置缓存
        /// </summary>
        public static List<PreFileInfo> PreFileCache { 
            get
            {
                _preFileCache ??= new List<PreFileInfo>();
                return _preFileCache;
            }
        }

        #endregion

        #region 工具方法
        
        /// <summary>
        /// 递归执行
        /// </summary>
        /// <param name="isBack">
        /// 是否由深入浅执行
        /// </param>
        public static void Recursion(DirectoryInfo baseDir,Action<DirectoryInfo> dirFunc,Action<FileInfo> fileFunc,bool isBack = false) {
            DirectoryInfo[] dirs = baseDir.GetDirectories();
            FileInfo[] files = baseDir.GetFiles();
            if (!isBack) {
                foreach (var fl in files)
                {
                    fileFunc(fl);
                }
            }

            foreach (var dir in dirs)
            {
                dirFunc(dir);
            }

            if (isBack) {
                foreach (var fl in files)
                {
                    fileFunc(fl);
                }
            }
        }

        public static string getPath(string fileName, string username) { 
            DateTime now = DateTime.Now;
            string dirPath = Path.Combine(MateData.BaseUrl, "files", username,
                now.Year.ToString(),
                now.Month.ToString(),
                now.Day.ToString());

            Directory.CreateDirectory(dirPath);

            string url = Path.Combine(dirPath, fileName);
            int index = 1;
            while (File.Exists(url)) { 
                url = Path.Combine(dirPath,
                    $"{Path.GetFileNameWithoutExtension(fileName)}({index++}){Path.GetExtension(fileName)}");
            }

            return url;
        }



        #endregion


    }
}
